//
//  MBDMineViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/3/19.
//

import Foundation
import UIKit
import YYText
import JLRoutes
import Kingfisher
import SnapKit

class MBDMineViewController : MBDBaseViewController {
    private var viewModel = MBDMineViewModel()
    private let tableView = UITableView(frame: .zero, style: .plain) // 使用 plain 样式

    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        // 使用 SnapKit 设置 TableView 的约束，让其从屏幕顶部开始
        tableView.snp.makeConstraints { make in
            make.edges.equalToSuperview() // 填充整个父视图
        }
        
        tableView.setDynamicBackgroundColor()
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        // 设置 contentInset，使内容从导航栏下方开始
        let statusBarHeight = UIApplication.shared.statusBarFrame.height
        tableView.contentInset = UIEdgeInsets(top: -statusBarHeight, left: 0, bottom: 0, right: 0)
        tableView.scrollIndicatorInsets = tableView.contentInset // 同步滚动条的 inset
        
        tableView.dataSource = self
        tableView.delegate = self
        tableView.estimatedRowHeight = 10

        tableView.register(MBDAvaterCell.self, forCellReuseIdentifier: "MBDAvaterCell")
        tableView.register(MBDIconTitleCommonCell.self, forCellReuseIdentifier: "MBDIconTitleCommonCell")
        tableView.register(MBDMineEmptyCell.self, forCellReuseIdentifier: "MBDMineEmptyCell")
        tableView.register(MBDForgroundEmptyCell.self, forCellReuseIdentifier: "MBDForgroundEmptyCell")
        
        NotificationCenter.default.addObserver(self, selector: #selector(userInfoUpdated), name: NSNotification.Name(rawValue: "UserInfoUpdated"), object: nil)
        
        self.view.setDynamicBackgroundColor()
        self.tableView.setDynamicBackgroundColor()

    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // 确保系统导航栏显示，并使用自定义外观
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    // 更新导航栏的透明度
    private func updateNavBarAlpha(_ alpha: CGFloat) {
        // 设置导航栏及其子视图的透明度
        navigationController?.navigationBar.subviews.first?.alpha = alpha
    }
    
    @objc func userInfoUpdated(){
        self.viewModel.cellModels = MBDMineViewModel.defaultCellModels

        self.tableView.reloadData()
    }
    
    func updateUI(){
        self.tableView.reloadData()
    }
    
    override func updateColors() {
        tableView.setDynamicBackgroundColor()
        self.viewModel.cellModels = MBDMineViewModel.defaultCellModels
        self.tableView.reloadData()
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        if traitCollection.userInterfaceStyle == .dark {
            return .lightContent  // 暗黑模式下，状态栏文字为白色
        } else {
            if #available(iOS 13.0, *) {
                return .darkContent
            } else {
                // Fallback on earlier versions
                return .default
            }   // 浅色模式下，状态栏文字为黑色 (iOS 13 及之后)
            
        }
    }
    
    override var prefersStatusBarHidden: Bool {
        return false // 返回 true 表示隐藏状态栏
    }

}

extension MBDMineViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels[indexPath.row]
        
        if cellModel is MBDForgroundEmptyCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDForgroundEmptyCell", for: indexPath)
            let realCell = cell as! MBDForgroundEmptyCell
            realCell.cellModel = cellModel
            return cell
        }
        
        if cellModel is MBDMineAvatarCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDAvaterCell", for: indexPath)
            let realCell = cell as! MBDAvaterCell
            realCell.cellModel = cellModel
            return cell
        } else if cellModel is MBDMineEmptyCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDMineEmptyCell", for: indexPath)
            return cell
        } else if cellModel is MBDMineCommonCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDIconTitleCommonCell", for: indexPath)
            let realCell = cell as! MBDIconTitleCommonCell
            let realCellModel = cellModel as! MBDMineCommonCellModel

            realCell.cellModel = realCellModel
            return cell
        }
        return UITableViewCell()
    }
}


extension MBDMineViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        let cellModel = self.viewModel.cellModels[indexPath.row]
        if cellModel is MBDMineCommonCellModel {
            let realItem = cellModel as! MBDMineCommonCellModel
            JLRoutes.routeURL(URL(string: realItem.nextVCURLString ?? ""))
        }
        
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels[indexPath.row] as! MBDCommonCellModel
        return cellModel.cellHeight()
    }
}
